using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Quartz;
using RuYiAdmin.Net.WebApi.AppCode.Extensions;
using RuYiAdmin.Net.WebApi.AppCode.Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace RuYiAdmin.Net.WebApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }).ConfigureAppConfiguration((hostingContext, config) =>
                {
                    var basePath = Directory.GetCurrentDirectory();
                    var directory = Path.Join(basePath, "SqlConfig");
                    var files = Directory.GetFiles(directory, "*.config", SearchOption.AllDirectories);

                    foreach (var file in files)
                    {
                        //SQL文件热更新
                        config.AddXmlFile(file, optional: true, reloadOnChange: true);
                    }

                    //配置文件热更新
                    config.AddJsonFile(Path.Join(basePath, "appsettings.json"), optional: true, reloadOnChange: true);
                }).UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureServices((hostContext, services) =>
            {
                //注册Quartz
                services.AddQuartz(q =>
                {
                    q.UseMicrosoftDependencyInjectionScopedJobFactory();

                    // Register the job, loading the schedule from configuration
                    q.AddJobAndTrigger<HelloWorldJob>(hostContext.Configuration);
                });

                services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
            });
    }
}
